<?php defined('SYSPATH') or die('No direct script access.');

/**
 *退件包裹处理
 * @package  qcwo
 * @author   taj
 */
class Controller_Returnedparcel extends Controller_Admin
{
    /**
     *退件处理权限
     */
    public function before()
    {
        try{
            ACL::Required('create returnedparcel');
        }catch(HTTP_Exception_403 $e){
            Message::error('sorry，你没有权限进这个目录');
            $this->request->redirect(URL::base(TRUE));
        }
        parent::before();
    }

    /**
     *退件默认界面
     */
    public function action_index()
    {
        $this->title = __('扫描退件-新建退件接收单');
        $batches     = basic::get_batches();
        $view        = View::factory('inventory/returnedparcel')
            ->set('batches',$batches);

        $this->response->body($view);
    }

    public function action_insert()
    {
        $erp_orderid = '';
        $warehouseid = Kohana::$config->load('warehouse')->warehouse_id;
        if(isset($_GET['erp_orderid'])){
            //$erp_orderid=str_replace('E','',trim($_GET['erp_orderid']));
            $erpold_orderid = trim($_GET['erp_orderid']);
        }

        $reason_id = isset($_GET['reason'])?$_GET['reason']:0;
        $pici      = isset($_GET['pici'])?$_GET['pici']:'';

        $new_erp_userid = User::active_user()->id;
        // yuqing -- begin 去除老erp的id验证 日志中为进销存的用户id
//        $old_userid     = service_olduser::Get_old_user_by_new_id($new_erp_userid);
        $old_userid['id'] = $new_erp_userid;
        //yuqing -- end
        if(empty($old_userid)){
            echo json_encode(array(
                'did'    => 'N',
                'reason' => '此用户帐号没有进销存用户id，不可以操作此功能'
            ));
            exit;
        }


        if($erpold_orderid==''){
            echo json_encode(array(
                'did'    => 'N',
                'reason' => '扫描订单号为空'
            ));
            exit;
        }

        if($pici==''){
            echo json_encode(array(
                'did'    => 'N',
                'reason' => '输入的批次号为空'
            ));
            exit;
        }

        $select_batch = ORM::factory('returned_batch')
            ->where('batch_code','=',$pici)
            ->find();
        if($select_batch->id==''){
            echo json_encode(array(
                'did'    => 'N',
                'reason' => '输入的批次号不存在，请重新输入正确的批次号'
            ));
            exit;
        }

        if(substr($erpold_orderid,0,1)=='e'||substr($erpold_orderid,0,1)=='E'){

            if(strlen($erpold_orderid) > 13){
                $erp_orderid = substr($erpold_orderid,1,13);
            }else{
                $erp_orderid = substr($erpold_orderid,1,10);
            }

            $sql_erporders = "SELECT erp_orders_id,ebay_orders_id,shipping_method,orders_mail_code,orders_shipping_code
			                FROM erp_orders WHERE erp_orders_id='".$erp_orderid."' limit 1";
            $erporders     = DB::query(Database::SELECT,$sql_erporders)
                ->execute('readonlyerp')
                ->as_array();
            $erporders1    = $erporders2 = array();
            if(empty($erporders)){
                $sql_erporders1 = "SELECT erp_orders_id,ebay_orders_id,shipping_method,orders_mail_code,orders_shipping_code
			                FROM erp_orders1 WHERE erp_orders_id='".$erp_orderid."' limit 1";
                $erporders1     = DB::query(Database::SELECT,$sql_erporders1)
                    ->execute('readonlyerp')
                    ->as_array();

                $sql_erporders2 = "SELECT erp_orders_id,ebay_orders_id,shipping_method,orders_mail_code,orders_shipping_code
			                FROM erp_orders2 WHERE erp_orders_id='".$erp_orderid."' limit 1";
                $erporders2     = DB::query(Database::SELECT,$sql_erporders2)
                    ->execute('readonlyerp')
                    ->as_array();
            }
        }else{
            $sql_erporders = "SELECT erp_orders_id,ebay_orders_id,shipping_method,orders_mail_code,orders_shipping_code
			                FROM erp_orders WHERE orders_mail_code='".$erpold_orderid."' OR orders_shipping_code = '".$erpold_orderid."' limit 1";
            $erporders     = DB::query(Database::SELECT,$sql_erporders)
                ->execute('readonlyerp')
                ->as_array();

            $erporders1 = $erporders2 = array();
            if(empty($erporders)){
                $sql_erporders1 = "SELECT erp_orders_id,ebay_orders_id,shipping_method,orders_mail_code,orders_shipping_code
			                FROM erp_orders1 WHERE orders_mail_code='".mysql_escape_string($erpold_orderid)."' OR orders_shipping_code = '".$erpold_orderid."' limit 1";
                $erporders1     = DB::query(Database::SELECT,$sql_erporders1)
                    ->execute('readonlyerp')
                    ->as_array();

                $sql_erporders2 = "SELECT erp_orders_id,ebay_orders_id,shipping_method,orders_mail_code,orders_shipping_code
			                FROM erp_orders2 WHERE orders_mail_code='".mysql_escape_string($erpold_orderid)."' OR orders_shipping_code = '".$erpold_orderid."' limit 1";
                $erporders2     = DB::query(Database::SELECT,$sql_erporders2)
                    ->execute('readonlyerp')
                    ->as_array();
            }

            $erp_orderid = 0;
            if(!empty($erporders)){
                $erp_orderid = $erporders[0]['erp_orders_id'];
            }

            if(!empty($erporders1)){
                $erp_orderid = $erporders1[0]['erp_orders_id'];
            }

            if(!empty($erporders2)){
                $erp_orderid = $erporders2[0]['erp_orders_id'];
            }
        }

        if(empty($erporders)&&empty($erporders1)&&empty($erporders2)){
            echo json_encode(array(
                'did'    => 'N',
                'reason' => '输入的订单号错误，erp数据库里不存在该订单号或追踪码'.$erpold_orderid
            ));
            exit;
        }

        $select_parcel = ORM::factory('returned_parcel')
            ->where('erp_order_id','=',$erp_orderid)
            ->find();
        if($select_parcel->id!=''){
            echo json_encode(array(
                'did'    => 'N',
                'reason' => $select_parcel->erp_order_id.'该订单退件已扫描过，扫描批次号是'.$select_parcel->returned_batch_code
            ));
            exit;
        }

        $sql_erp_orderproducts = "SELECT orders_products_id,erp_orders_id,orders_sku,products_place,orders_item,
			                    item_count FROM erp_orders_products WHERE erp_orders_id=".$erp_orderid;
        $erp_orderproducts     = DB::query(Database::SELECT,$sql_erp_orderproducts)
            ->execute('readonlyerp')
            ->as_array();

        $erp_orderproducts1 = $erp_orderproducts2 = array();
        if(empty($erp_orderproducts)){
            $sql_erp_orderproducts1 = "SELECT orders_products_id,erp_orders_id,orders_sku,products_place,orders_item,
			                    item_count FROM erp_orders_products1 WHERE erp_orders_id=".$erp_orderid;
            $erp_orderproducts1     = DB::query(Database::SELECT,$sql_erp_orderproducts1)
                ->execute('readonlyerp')
                ->as_array();
            $sql_erp_orderproducts2 = "SELECT orders_products_id,erp_orders_id,orders_sku,products_place,orders_item,
			                    item_count FROM erp_orders_products2 WHERE erp_orders_id=".$erp_orderid;
            $erp_orderproducts2     = DB::query(Database::SELECT,$sql_erp_orderproducts2)
                ->execute('readonlyerp')
                ->as_array();
        }

        if(empty($erp_orderproducts)&&empty($erp_orderproducts1)&&empty($erp_orderproducts2)){
            echo json_encode(array(
                'did'    => 'N',
                'reason' => '输入的订单号,在erp下没有物品信息'.$erp_orderid
            ));
            exit;
        }

        $statusdics     = ORM::factory('statusdic')
            ->where('table','=','returned_parcels')
            ->where('number','=',$reason_id)
            ->where('colum_name','=','returned_reason')
            ->find();
        $reason_content = $statusdics->value;

        if($reason_id==1||$reason_id==2){
            $erp_op_id = 2;
            $type      = 13;
        }else{
            $erp_op_id = 8;
            $type      = 68;
        }

        if(empty($erporders)){
            if(!empty($erporders1)){
                $sql_update_order_status = "UPDATE erp_orders1 SET erp_op_id=".$erp_op_id." WHERE erp_orders_id='".$erp_orderid."'";
                $sql_erp_logs            = "INSERT INTO erp_ebay_log1(erp_orders_id,cotent,writetime,writeer,types) VALUES ('".$erp_orderid."','".$reason_content."','".date('Y-m-d H:i:s')."','".$old_userid['id']."','".$type."')";
            }
            if(!empty($erporders2)){
                $sql_update_order_status = "UPDATE erp_orders2 SET erp_op_id=".$erp_op_id." WHERE erp_orders_id='".$erp_orderid."'";
                $sql_erp_logs            = "INSERT INTO erp_ebay_log2(erp_orders_id,cotent,writetime,writeer,types) VALUES ('".$erp_orderid."','".$reason_content."','".date('Y-m-d H:i:s')."','".$old_userid['id']."','".$type."')";
            }
        }else{
            $sql_update_order_status = "UPDATE erp_orders SET erp_op_id=".$erp_op_id." WHERE erp_orders_id='".$erp_orderid."'";
            $sql_erp_logs            = "INSERT INTO erp_ebay_log(erp_orders_id,cotent,writetime,writeer,types) VALUES ('".$erp_orderid."','".$reason_content."','".date('Y-m-d H:i:s')."','".$old_userid['id']."','".$type."')";
        }

        DB::query(Database::UPDATE,$sql_update_order_status)
            ->execute('readonlyerp');
        DB::query(Database::UPDATE,$sql_erp_logs)
            ->execute('readonlyerp');

        if(empty($erporders)){
            if(!empty($erporders1)){
                $erporders = $erporders1;
            }
            if(!empty($erporders2)){
                $erporders = $erporders2;
            }
        }

        $tracenumber = ($erporders[0]['orders_mail_code']==''||$erporders[0]['orders_mail_code']==NULL)?$erporders[0]['orders_shipping_code']:$erporders[0]['orders_mail_code'];

        if(empty($erp_orderproducts)){
            if(!empty($erp_orderproducts1)){
                $erp_orderproducts = $erp_orderproducts1;
            }

            if(!empty($erp_orderproducts2)){
                $erp_orderproducts = $erp_orderproducts2;
            }
        }
        foreach($erp_orderproducts as $erpop){
            $returned_parcels                       = ORM::factory('Returnedparcel');
            $returned_parcels->warehouseid          = $warehouseid;
            $returned_parcels->erp_order_id         = $erporders[0]['erp_orders_id'];
            $returned_parcels->ebay_orders_id       = $erporders[0]['ebay_orders_id'];
            $returned_parcels->shipping_method      = $erporders[0]['shipping_method'];
            $returned_parcels->orders_shipping_code = $tracenumber;
            $returned_parcels->created              = date('Y-m-d H:i:s');
            $returned_parcels->userid               = User::active_user()->id;
            $returned_parcels->returned_batch_code  = $pici;
            $returned_parcels->returned_reason      = $reason_id;
            $returned_parcels->sku                  = strtoupper(trim($erpop['orders_sku']));
            $returned_parcels->num                  = $erpop['item_count'];
            //yuqing   --begin--
//            $do                                     = ORM::factory('deliveryorder')
//                ->where('orders_products_id','=',$erpop['orders_products_id'])
//                ->find();
//            if($do->id!=''){
//
//                $returned_parcels->single_price = $do->single_price;
//                $returned_parcels->money        = $do->single_price*$erpop['item_count'];
//                $returned_parcels->cost         = $do->single_price*$erpop['item_count'];
//            }else{
            //yuqing   -- end --
//                $supplier                       = new Service_Common();
//                $result                         = json_encode($supplier->get_sku_price($returned_parcels->sku)); //若出库价为0就获取系统默认价
//                $price = Skusystemapi::getSkuPrice($returned_parcels->sku);
//                $price = $price[0]['num'] ? $price[0]['num'] : 0;
                $skuPriceArr = hznewerpclient::getNewPrice(array($returned_parcels->sku));
                $price = $skuPriceArr[$returned_parcels->sku];
                $returned_parcels->single_price = $price;
                $returned_parcels->money        = $price*$erpop['item_count'];
                $returned_parcels->cost         = $price*$erpop['item_count'];
            //--yuqing --bedgin ---
//            }
            //  --  yuqing -- end ---
            //START     ----------------------------------CWY更新代码-------------------------------------
            /**
             * 查询中文名称和储位
             */
            $cnname                              = Skusystemapi::getSkuCnname($erpop['orders_sku']);
            $erp_products[0]['products_name_cn'] = $cnname[0]['name'];
            $place                               = Skusystemapi::getSkuPlace($erpop['orders_sku']);
            $erp_products[0]['products_place']   = isset($place[0]['place'])?$place[0]['place']:'';

            //            $sql_products = "SELECT products_name_cn,products_place FROM erp_products_data
            //            WHERE products_sku='".$erpop['orders_sku']."'";
            //			$erp_products = DB::query(Database::SELECT,$sql_products)->execute('readonlyerp')->as_array();
            //END       ----------------------------------CWY更新代码-------------------------------------
            if(empty($erp_products)){
                $returned_parcels->sku_name         = '';
                $returned_parcels->storage_position = '';
            }else{
                $returned_parcels->sku_name         = $erp_products[0]['products_name_cn'];
                $returned_parcels->storage_position = $erp_products[0]['products_place'];
            }

            $returned_parcels->save();
        }

        echo json_encode(array(
            'did'         => 'Y',
            'erporderid'  => $erporders[0]['erp_orders_id'],
            'tracenumber' => $tracenumber,
            'traceway'    => $erporders[0]['shipping_method']
        ));
        exit;
    }

    public function action_createdbatch()
    {

        $this->title      = __('扫描退件-新建退件接收单');
        $batch_code1      = date('Ymd');
        $userid           = str_pad(User::active_user()->id,4,"0",STR_PAD_LEFT);
        $batch_code       = $batch_code1.$userid;
        $returned_batches = ORM::factory('returned_batch')
            ->where('batch_code','LIKE',$batch_code.'%')
            ->order_by('id','DESC')
            ->find();

        if($returned_batches->id!=''){
            $id = substr($returned_batches->batch_code,-3);
            $id = $id+1;
        }else{
            $id = 001;
        }
        $id           = str_pad($id,3,"0",STR_PAD_LEFT);
        $newbatchcode = $batch_code.$id;

        $insert_batch             = ORM::factory('returned_batch');
        $insert_batch->batch_code = $newbatchcode;
        $insert_batch->created    = date('Y-m-d H:i:s');
        $insert_batch->userid     = User::active_user()->id;
        $insert_batch->save();

        if($insert_batch->saved()){
            Message::success($newbatchcode.'新批次号已生成成功');
        }else{
            Message::error('新批次号生成失败');
        }

        $batches = basic::get_batches(); //批次号文本框提示语
        $view    = View::factory('inventory/returnedparcel')
            ->set('batches',$batches);

        $this->response->body($view);
    }


    public function action_down_returned()
    {
        set_time_limit(0);
        ini_set('memory_limit','512M');

        $user = ORM::factory('user',User::active_user()->id);
        require_once(Kohana::find_file('vendor','PHPExcel/PHPExcel/IOFactory'));
        $this->objReader = PHPExcel_IOFactory::createReader('Excel5');
        $objPHPExcel     = new PHPExcel();
        $objPHPExcel->getProperties()
            ->setCreator("ROMWE")
            ->setLastModifiedBy("ROMWE")
            ->setTitle("Office 2003 XLSX Test Document")
            ->setSubject("Office 2003 XLSX Test Document")
            ->setDescription("Test document for Office 2003 XLSX, generated using PHP classes.")
            ->setKeywords("office 2003 openxml php")
            ->setCategory("Test result file");
        $objActSheet = $objPHPExcel->setActiveSheetIndex(0);
        $objActSheet->setCellValue('A1','序号');
        $objActSheet->setCellValue('B1','erp订单号');
        $objActSheet->setCellValue('C1','标记状态');
        $objActSheet->setCellValue('D1','挂号单号');
        $objActSheet->setCellValue('E1','账户');
        $objActSheet->setCellValue('F1','货代代码');
        $objActSheet->setCellValue('G1','国家（中文）');
        $objActSheet->setCellValue('H1','国家（英文）');
        $objActSheet->setCellValue('I1','发货时间');
        $objActSheet->setCellValue('J1','sku');
        $objActSheet->setCellValue('K1','sku中文名称');
        $objActSheet->setCellValue('L1','储位');
        $objActSheet->setCellValue('M1','数量');
        $objActSheet->setCellValue('N1','备注');

        $pi      = $_GET['pici'];
        $parcels = ORM::factory('returned_parcel')
            ->where('returned_batch_code','=',$pi)
            ->order_by('created','DESC')
            ->find_all();

        $i = 2;
        $j = 1;
        foreach($parcels as $parcel){

            $objActSheet->setCellValue('A'.$i,$j);
            $objActSheet->setCellValue('B'.$i,$parcel->erp_order_id);

            if($parcel->erp_order_id!=''){
                $sql_erp_orders = "SELECT `erp_op_id`,`orders_out_time`,`sales_account`,`erp_post_office`,buyer_country FROM `erp_orders` WHERE `erp_orders_id`='".$parcel->erp_order_id."' limit 1";
                $eo             = DB::query(Database::SELECT,$sql_erp_orders)
                    ->execute('readonlyerp')
                    ->as_array();

                $erporders1 = $erporders2 = array();
                if(empty($eo)){
                    $sql_erporders1 = "SELECT `erp_op_id`,`orders_out_time`,`sales_account`,`erp_post_office`,buyer_country FROM erp_orders1 WHERE erp_orders_id='".$parcel->erp_order_id."' limit 1";
                    $erporders1     = DB::query(Database::SELECT,$sql_erporders1)
                        ->execute('readonlyerp')
                        ->as_array();

                    $sql_erporders2 = "SELECT `erp_op_id`,`orders_out_time`,`sales_account`,`erp_post_office`,buyer_country FROM erp_orders2 WHERE erp_orders_id='".$parcel->erp_order_id."' limit 1";
                    $erporders2     = DB::query(Database::SELECT,$sql_erporders2)
                        ->execute('readonlyerp')
                        ->as_array();
                }

                if(empty($eo)){
                    if(!empty($erporders1)){
                        $eo = $erporders1;
                    }else{
                        $eo = $erporders2;
                    }
                }

                if(!empty($eo[0])){
                    $sql_co = "SELECT country_en,country_cn FROM erp_country WHERE country_en='".mysql_escape_string($eo[0]['buyer_country'])."'";
                    $co     = DB::query(Database::SELECT,$sql_co)
                        ->execute('readonlyerp')
                        ->as_array();

                    if(!empty($co[0]['country_cn'])){
                        $cn_name = $co[0]['country_cn'];
                        $en_name = $co[0]['country_en'];
                    }else{
                        $cn_name = '';
                        $en_name = '';
                    }
                    if($eo[0]['erp_op_id']==2){
                        $notice = "标记成功";
                    }else{
                        $notice = "标记不成功";
                    }
                    $objActSheet->setCellValue('C'.$i,$notice);
                    $objActSheet->setCellValue('D'.$i,$parcel->orders_shipping_code);
                    $objActSheet->setCellValue('E'.$i,$eo[0]['sales_account']);
                    $objActSheet->setCellValue('F'.$i,$eo[0]['erp_post_office']);
                    $objActSheet->setCellValue('G'.$i,$cn_name);
                    $objActSheet->setCellValue('H'.$i,$en_name);
                    $objActSheet->setCellValue('I'.$i,$eo[0]['orders_out_time']);
                }
            }

            $objActSheet->setCellValue('J'.$i,$parcel->sku);
            $objActSheet->setCellValue('K'.$i,$parcel->sku_name);
            $objActSheet->setCellValue('L'.$i,$parcel->storage_position);
            $objActSheet->setCellValue('M'.$i,$parcel->num);

            $i++;
            $j++;
        }

        $i++;
        $objActSheet->setCellValue('B'.$i,'批次号');
        $objActSheet->setCellValue('D'.$i,$_GET['pici']);
        $i++;
        $objActSheet->setCellValue('B'.$i,'交接人');
        $objActSheet->setCellValue('C'.$i,$user->nick);
        $objActSheet->setCellValue('D'.$i,'接收人');
        $i++;

        $objActSheet->setCellValue('B'.$i,'日期');
        $objActSheet->setCellValue('C'.$i,date('Y-m-d'));
        $objActSheet->setCellValue('D'.$i,'日期');

        $objPHPExcel->getActiveSheet()
            ->setTitle('退货清单');
        $objPHPExcel->setActiveSheetIndex(0);
        $day = date("Y-m-d-H");
        ob_end_clean();
        header("Content-Type: application/vnd.ms-excel; charset=utf-8");
        header('Content-Disposition: attachment;filename="'.$day.'退货清单.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel5');
        $objWriter->save('php://output');
        exit;
    }

    //手动录入退件物品资料
    public function action_shoudong_insert_parcel()
    {
        $warehouse_id = Kohana::$config->load('warehouse')->warehouse_id;
        $this->title  = __('手动录入-新建退件接收单');
        $batches      = basic::get_batches(); //批次号文本框提示语

        if(isset($_POST['skuinfo'])&&$_POST['skuinfo']){
            $sku_arr = json_decode($_POST['skuinfo'],TRUE);
            $user_id = User::active_user()->id;
            foreach($sku_arr as $sku_info){
                $sku        = strtoupper(trim($sku_info['sku']));
                $skuok      = intval($sku_info['skuok']);
                $skuno      = intval($sku_info['skuno']);
                $sum        = $skuok+$skuno;
                $sku_detail = basic::load_sku_info($sku);
                $pi         = trim($sku_info['pi']);
                $sku_name   = $sku_detail['products_name_cn'];
                $remark     = $sku_info['orderid']?'手动录入退货,订单号为'.$sku_info['orderid']:'手动录入退货';
                $remark .= ','.trim($sku_info['remark']);
                $sku_position = $sku_detail['products_place'];

                /**
                 * 获取SKU对应的采购员ID信息
                 * @time20140819
                 */
                if($sku){
                    $olderp_user_id   = qualityaction::getskuname($sku);
                    $olderp_user_name = qualityaction::geterpname($olderp_user_id['oper']);
                    $newerp_user_id   = qualityaction::getuserid($olderp_user_name);
                }
                $purchase_man = isset($newerp_user_id)?$newerp_user_id:0;

                $sql    = "INSERT INTO returned_parcels (`warehouseid`,`erp_order_id`,`created`,userid,returned_batch_code, `returned_reason`, `qc_user`,
			 `qc_time`, `sku`, `sku_name`, `storage_position`, `num`, `qualified_num`, `failure_num`,status) VALUES(".$warehouse_id.",".intval($sku_info['orderid']).",'".date('Y-m-d H:i:s')."',".$user_id.",'".$pi."',".intval($sku_info['reason']).",$user_id,
			 '".date('Y-m-d H:i:s')."','".mysql_escape_string($sku)."','".mysql_escape_string($sku_name)."',
			 '".mysql_escape_string($sku_position)."',$sum,$skuok,$skuno,20)";
                $insert = DB::query(Database::INSERT,$sql)
                    ->execute('newerp');

                if($skuok!=0){
                    //yuqing begin -- 更改单价为最新采购入库价
//                    if(intval($sku_info['orderid'])==''||intval($sku_info['orderid'])==0){
//                        $supplier     = new Service_Common();
//                        $result       = json_encode($supplier->get_sku_price($sku)); //若出库价为0就获取系统默认价
//                        $single_price = $result;
//                    }else{
//
//                        $do = ORM::factory('deliveryorder')
//                            ->where('orders_products_id','=',$sku_info['orderid'])
//                            ->find();
//                        if($do->id!=''&&$do->single_price!=0){
//                            $single_price = floatval($do->single_price);
//                        }else{
//                            $supplier     = new Service_Common();
//                            $result       = json_encode($supplier->get_sku_price($sku)); //若出库价为0就获取系统默认价
//                            $single_price = $result;
//                        }
//                    }
                    $single_price_arr = Hznewerpclient::getNewPrice(array($sku));
                    $single_price = $single_price_arr[$sku];
                    //end
                    $sql      = "INSERT INTO warehouseorders (`warehouseid`,`warehouse_date`, `op_time`,  `returned_parcel_id`,
	  			 `sku`, `sku_name`, `sku_standard`, `storage_position`, `warehouse_quantity`,single_price,money,cost,
	  			 `remark`, `type`, `warehouse_man`) VALUES($warehouse_id,"."
	  			 '".date('Y-m-d H:i:s')."','".date('Y-m-d H:i:s')."',".$insert[0].",'".mysql_escape_string($sku)."',
	  			 '".mysql_escape_string($sku_name)."','".mysql_escape_string($sku_detail['size'])."',
	  			 '".mysql_escape_string($sku_position)."',$skuok,$single_price,".$single_price*$skuok.",".$single_price*$skuok.",'".$remark."',20,$user_id)";
                    $myinsert = DB::query(Database::INSERT,$sql)
                        ->execute('newerp');
                }

                if($skuno!=0){
                    $sql      = "INSERT INTO unqualified_deal_invoices (`warehouseid`,`invoice_date`,`returned_parcel_id`, `sku`, `sku_name`,
	  			 `sku_standard`, `storage_position`, `quantity`,`purchase_man`, `quality_man`, `quality_remark`, `check_time`) VALUES($warehouse_id,"."
	  			 '".date('Y-m-d H:i:s')."',".$insert[0].",'".mysql_escape_string($sku)."','".mysql_escape_string($sku_name)."',
	  			 '".mysql_escape_string($sku_detail['size'])."','".mysql_escape_string($sku_position)."',
	  			 $skuno,$purchase_man,$user_id,'".$remark."','".date('Y-m-d H:i:s')."')";
                    $myinsert = DB::query(Database::INSERT,$sql)
                        ->execute('newerp');
                }
            }
            echo json_encode(1);
            exit;
        }
        //$batches = ORM::factory('returned_batch')->order_by('created','DESC')->limit('50')->find_all()->as_array();
        $view = View::factory('inventory/shoudongparcel')
            ->set('batches',$batches);
        $this->response->body($view);
    }

    //验证批次号
    public function action_notice_pi()
    {
        $batch = ORM::factory('returned_batch')
            ->where('batch_code','=',$_POST['select_pi'])
            ->find();
        if($batch->id==''){
            $jsonarr = array(
                'status' => 'n',
                'info'   => '输入的批次号不对，请重新输入'
            );
        }else{
            $jsonarr = array(
                'status' => 'y',
                'info'   => 'ok'
            );
        }

        echo json_encode($jsonarr);
        exit;
    }

    //验证订单号
    public function action_notice_order()
    {
        $sql_erporders = "SELECT erp_orders_id,ebay_orders_id,shipping_method,orders_mail_code,orders_shipping_code FROM erp_orders WHERE erp_orders_id='".$_POST['order_id']."' limit 1";
        $erporders     = DB::query(Database::SELECT,$sql_erporders)
            ->execute('readonlyerp')
            ->as_array();

        $erporders1 = $erporders2 = array();
        if(empty($erporders)){
            $sql_erporders1 = "SELECT erp_orders_id,ebay_orders_id,shipping_method,orders_mail_code,orders_shipping_code FROM erp_orders1 WHERE erp_orders_id='".$_POST['order_id']."' limit 1";
            $erporders1     = DB::query(Database::SELECT,$sql_erporders1)
                ->execute('readonlyerp')
                ->as_array();

            $sql_erporders2 = "SELECT erp_orders_id,ebay_orders_id,shipping_method,orders_mail_code,orders_shipping_code FROM erp_orders2 WHERE erp_orders_id='".$_POST['order_id']."' limit 1";
            $erporders2     = DB::query(Database::SELECT,$sql_erporders2)
                ->execute('readonlyerp')
                ->as_array();
        }

        if(empty($erporders)&&empty($erporders1)&&empty($erporders2)){
            $arr = array(
                'status' => 'n',
                'info'   => '输入的订单号错误，erp数据库里不存在该订单号'.$_POST['order_id']
            );
        }else{
            $arr = array(
                'status' => 'y',
                'info'   => 'ok'
            );
        }

        echo json_encode($arr);
        exit;
    }
}
